/**
 *
 * @author ilya portnyagin iportnyagin@gmail.com
 */

package ru.portnyagin.helpdeskru.controller;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import ru.portnyagin.helpdeskru.model.FileHD;
import ru.portnyagin.helpdeskru.model.HistoryRequest;
import ru.portnyagin.helpdeskru.model.Priority;
import ru.portnyagin.helpdeskru.model.Request;
import ru.portnyagin.helpdeskru.model.ServiceObject;
import ru.portnyagin.helpdeskru.model.StateRequest;
import ru.portnyagin.helpdeskru.model.UserHD;
import ru.portnyagin.helpdeskru.util.JsfUtil;


@ManagedBean(name = "currentRequestBean")
@ViewScoped
public class CurrentRequestBean implements Serializable {
    
    private Request current;
    private String actionString;
    private String addText;
    
    private List<ServiceObject> listServiceObject;
    private List<StateRequest> listStateRequest;
    private List<HistoryRequest> listChanges;
    private List<Request> listRequestsByServiceObject;
    private List<FileHD> listFiles;
    
    @ManagedProperty("#{loginController}")
    private LoginController loginController;

    @ManagedProperty("#{stateRequestBean}")
    private StateRequestBean stateRequestBean;
    
    private UserHD curUser;
    private String role;
    
    private boolean enableChangeDescription;
    private boolean enableAddText;
    private boolean enableAddFile;
    private boolean enableChangeServiceObject;
    private boolean enableChangePriority;
    private boolean enableChangeStateRequest;
    private boolean enableChangePerfomer;
    
    @EJB
    private ru.portnyagin.helpdeskru.service.RequestService requestService;

    @EJB
    private ru.portnyagin.helpdeskru.service.HistoryRequestService historyRequestService;

    @EJB
    private ru.portnyagin.helpdeskru.service.FileHDService fileHDService;

    @EJB
    private ru.portnyagin.helpdeskru.service.ServiceObjectService serviceObjectService;
       
    public CurrentRequestBean() {
    }
    
    @PostConstruct
    private void postConstruct() {
        curUser = loginController.getLogged();
        role = curUser.getRole().getName().name();
    }
    
    public String getAddText() {
        return addText;
    }

    public void setAddText(String addText) {
        this.addText = addText;
    }
    
    public Request getCurrent() {
        return current;
    }

        
        
    public String getActionString() {
        return actionString;
    }

    public void setActionString(String actionString) {
        this.actionString = actionString;
    }

    public void setLoginController(LoginController loginController) {
        this.loginController = loginController;
    }

    public void setStateRequestBean(StateRequestBean stateRequestBean) {
        this.stateRequestBean = stateRequestBean;
    }
    
    public boolean isEnableChangeDescription() {
        return enableChangeDescription;
    }

    public boolean isEnableAddText() {
        return enableAddText;
    }

    public boolean isEnableChangeServiceObject() {
        return enableChangeServiceObject;
    }

    public boolean isEnableChangePriority() {
        return enableChangePriority;
    }

    public boolean isEnableChangeStateRequest() {
        return enableChangeStateRequest;
    }

    public boolean isEnableChangePerfomer() {
        return enableChangePerfomer;
    }

    public boolean isEnableAddFile() {
        return enableAddFile;
    }


    public void update() {
        
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm dd.MM.yyyy");
        String dt = sdf.format(new Date());
        
        if (addText != null) {
            if (current.getText() != null) {
                current.setText(current.getText() + dt + " " + curUser.getName() + ": " + addText + "<br/>");
                addText = "";
            }
            else
            {
                current.setText(dt + " " + curUser.getName() + ": " + addText + "<br/>");
                addText = "";
            }
        }

        if (current.getId() == null) {     // новый запрос
            current.setCreatedDate(new Date());
        }
        
        requestService.update(current, curUser);
        
        for(FileHD f: listFiles) {
            if(f.getId() == null) {
                fileHDService.create(f);
            }
        }
    }
        
    
    public void handleFileUpload(FileUploadEvent event) {
        
        UploadedFile file = event.getFile();

        FileHD fileHD = new FileHD();
        
        fileHD.setName(file.getFileName());
        fileHD.setContent(file.getContents());
        fileHD.setUploadedDate(new Date());
        fileHD.setRequest(current);
        fileHD.setUploadedBy(curUser);
        listFiles.add(fileHD);
        
        JsfUtil.addSuccessMessage(ResourceBundle.getBundle("property",
                FacesContext.getCurrentInstance().getViewRoot().getLocale()).
                getString("fileUploaded") + " " + file.getFileName());
    }      



    public List<HistoryRequest> getListChanges() {
        if(current == null) {
            return null;
        }
        if(listChanges == null) {
            listChanges = new ArrayList<>();
            listChanges = historyRequestService.find(current);
        }
        return listChanges;
    }

    
    public List<FileHD> getListFiles() {
        if(current == null) {
            return null;
        }
        if(listFiles == null) {
            listFiles = new ArrayList<>();
            listFiles = fileHDService.findByRequest(current);
        }
        return listFiles;
    }
    
    public List<Request> getListRequestsByServiceObject() {
        if(current == null) {
            return null;
        }
        if(listRequestsByServiceObject == null) {
            listRequestsByServiceObject = new ArrayList<>();
            listRequestsByServiceObject = requestService.findByServiceObject(current);
        }
        return listRequestsByServiceObject;
    }
 
    
    public SelectItem[] getSelectItemsAvailableStateRequest() {
        if(current == null) {
            return null;
        }
        if(listStateRequest == null) {
            listStateRequest = new ArrayList<>();
            listStateRequest = stateRequestBean.getListAvailableStateRequest(current.getStateRequest().getId());
        }
        return JsfUtil.getSelectItems(listStateRequest, false);
    }
    
    public SelectItem[] getSelectItemServiceObject() {
        if(listServiceObject == null) {
            listServiceObject = new ArrayList<>();
            if(role.equals("CUSTOMER")) { // заказчик видит объекты только своей организации
                listServiceObject = serviceObjectService.findServiceObject(curUser); // тоже можно загнать в сессионный бин, а не запрашивать
            }
            else {
                listServiceObject = serviceObjectService.findAll();
            }
        }
        return JsfUtil.getSelectItems(listServiceObject, true);
    }
    
    
    public void setCurrent(Request current) {
        
        // если current == null - выход
        // опять выбрана ссылка на "текущий"/прежний запрос - выход
        if(current == null) { 
            return;
        }
        
        if(this.current == current) { 
            return;
        }
        
        listChanges = null; // ставим в null, чтобы обновить для выбранного запроса
        listFiles = null;   // будут возвращены через getListChanges и getListFiles
        listStateRequest = null;
        listRequestsByServiceObject = null;
        
        if(current.getId() == null) { // новая
            
            enableChangeDescription = true;
            enableAddText = true;
            enableChangeServiceObject = true;
            enableChangePriority = true;
            enableChangeStateRequest = false;
            enableChangePerfomer = false;
            enableAddFile = true; 
            
//            current.setStateRequest(new StateRequest("OPENED")); // взять из базы, т.к. в данном случае не будет названия до сохранения
            current.setStateRequest(stateRequestBean.getMapStateRequest().get("OPENED")); 
            current.setCreatedBy(curUser);
            current.setPriority(new Priority("MIDDLE"));
            
        } else { // не новая
        
            String stateRequest = current.getStateRequest().getId();
        
            if( stateRequest.equals("DONE") ||
                stateRequest.equals("NEEDINFO")) {

                if(role.equals("CUSTOMER")) { // роль заказчика
                    enableChangeDescription = true;
                    enableAddText = true;
                    enableChangeServiceObject = true;
                    enableChangePriority = true;
                    enableChangeStateRequest = true; 
                    enableChangePerfomer = false;
                    enableAddFile = true;
                } else {    // роль исполнителя
                    enableChangeDescription = false;
                    enableAddText = true;
                    enableChangeServiceObject = false;
                    enableChangePriority = false;
                    enableChangeStateRequest = false;
                    enableChangePerfomer = false;
                    enableAddFile = false;
                }
            }

            if( stateRequest.equals("OPENED") ||
                stateRequest.equals("INPROGRESS") ||
                stateRequest.equals("HOLDED") ||
                stateRequest.equals("REOPENED")) { 

                if(role.equals("CUSTOMER")) { // роль заказчика
                    enableChangeDescription = false;
                    enableAddText = true;
                    enableChangeServiceObject = false;
                    enableChangePriority = false;
                    enableChangeStateRequest = false;
                    enableChangePerfomer = false;
                    enableAddFile = false;
                    
                } else {        // роль исполнителя
                    enableChangeDescription = false;
                    enableAddText = true;
                    enableChangeServiceObject = false;
                    enableChangePriority = false;
                    enableChangeStateRequest = true;
                    enableChangePerfomer = true;
                    enableAddFile = true;
                    
                }
            }

            if(stateRequest.equals("CLOSED")) { // завершена
                    enableChangeDescription = false;
                    enableAddText = false;
                    enableChangeServiceObject = false;
                    enableChangePriority = false;
                    enableChangeStateRequest = false;
                    enableChangePerfomer = false;
                    enableAddFile = false;
            }
        }
        
        this.current = current;    
        
    }
     
    
    
    
    
}
